package com.chaofan.authsso.core.web;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.chaofan.authsso.core.common.Constant;
import com.chaofan.authsso.core.common.Methods;
import com.chaofan.authsso.core.common.SessionAndToken;
import com.chaofan.authsso.core.properties.SsoCoreProperties;
import com.chaofan.authsso.core.service.CacheInstance;
import com.chaofan.authsso.core.util.CacheKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录跳转
 * Author: Chaofan
 * Date: 2020/6/5 13:49
 * email: chaofan2685@qq.com
 */
@RequestMapping(value = "/authsso/login")
public class AuthController extends Methods {

    @Autowired
    SsoCoreProperties properties;

    @Autowired
    HttpSession session;

    @Autowired
    CacheInstance cacheInstance;

    @RequestMapping(value = "/{authcode}")
    public void login(@PathVariable String authcode, String redirectUri, HttpServletResponse response) throws IOException {
        //UrlDecode参数
        if (StrUtil.isEmpty(redirectUri)){
            error(response, Constant.NO_REDIRECT_URI_MSG);
            return;
        }
        redirectUri = URLUtil.decode(redirectUri);
        //查找验证码对应的token,找不到则跳转错误页
        SessionAndToken sessionAndToken = (SessionAndToken) cacheInstance.get(CacheKeyUtil.authCodeKey(authcode));
        if (sessionAndToken == null){
            error(response, Constant.NO_FIND_TOKEN_BY_CODE);
            return;
        }
        //查找这个会话的token(可能为空)
        String sessionToken = (String) session.getAttribute(Constant.SESSION_TOKEN_KEY);
        //查找该token的登录状态(可能为空)
        Object loginStatus = cacheInstance.get(CacheKeyUtil.tokenKey(sessionToken));
        if (StrUtil.isNotEmpty(sessionToken) && loginStatus != null){
            //如果已经登录过,将验证码对应的token存入缓存,以便以后取出替换
            cacheInstance.set(CacheKeyUtil.applyTokenKey(sessionAndToken.getToken()),sessionToken,60);
            //重定向到redirectUri
            response.sendRedirect(redirectUri);
        }else {
            //如果没有登录过,将验证码对应的token和redirectUri存入session,以便在登录成功后取用
            session.setAttribute(Constant.SESSION_TOKEN_KEY,sessionAndToken.getToken());
            session.setAttribute(Constant.SESSION_REDIRECT_URI_KEY,redirectUri);
            //重定向到登录页
            response.sendRedirect(properties.getLoginHtml());
        }
        cacheInstance.del(CacheKeyUtil.authCodeKey(authcode));
        cacheInstance.del(CacheKeyUtil.sessionCodeKey(sessionAndToken.getSessionId()));
        return;
    }

    private void error(HttpServletResponse response,String errorMsg) throws IOException {
        session.setAttribute(Constant.ERROR_MSG_KEY,errorMsg);
        response.sendRedirect(Constant.ERROR_HTML);
    }

}
